#include "callback.h"
#include "parse.h"
#include "upload.h"
#include "zlib.h"

Callback::Callback( QObject* parent  ) :
  QObject( parent )
{
};

Callback::~Callback() {
  auth = QString::null;

};


void Callback::authReq(int id, bool ok) {

  QString str = http->readAll().data();
  
  QStringList keys = str.split("\n");
  if (str.contains("Auth")) {
    qDebug() << "Got auth!";
    auth = keys[keys.count() -2].split("=")[1];
    qDebug() << auth;
    groupsRequest();
  }

  

  
};

void Callback::groupsRequest() {
  qDebug() << "requesting group data";
  http = new QHttp();

  QHttpRequestHeader header(
      "GET" ,
      "/m8/feeds/groups/default/full"
  );
  header.setValue ("Authorization",  "GoogleLogin auth="+auth);
  header.setValue("Host", "www.google.com");
  header.setValue("Accept-Encoding",  "gzip");
  //header.setValue( "User-Agent", "GQSync (gzip enabled)");

  http->setHost("www.google.com");
  http->request(header);

  QObject::connect(http, SIGNAL(done(bool)), this,SLOT(groupsFetched(bool)));


}

void Callback::groupsFetched( bool err) {


  QString str = QString::fromUtf8 ( http->readAll().data() );
  if (!err) {
    qDebug() << "We have group data" ;
    groupmap = parseGroups(str);
    contactsRequest();
  } else {
    qDebug() << "No data. Error: " << err;
  }

}

void Callback::contactsRequest() {
  qDebug() << "requesting contacts data";
  http = new QHttp();

  QHttpRequestHeader header(
      "GET" ,
      "/m8/feeds/contacts/default/full"
  );
  header.setValue ("Authorization",  "GoogleLogin auth="+auth);
  header.setValue("Host", "www.google.com");
  header.setValue("Accept-Encoding",  "gzip");
  //header.setValue( "User-Agent", "GQSync (gzip enabled)");

  http->setHost("www.google.com");
  http->request(header);

  QObject::connect(http, SIGNAL(done(bool)), this,SLOT(contactsFetched(bool)));



}

void Callback::contactsFetched( bool err) {


  QString str = QString::fromUtf8 ( http->readAll().data() );
  if (!err) {
    qDebug() << "We have contacts data";
    QMap<QString,QString> idmap = parseContacts(str,groupmap);
    upload(idmap);
  } else {
    qDebug() << "No data. Error: " << err;
  }

}

void Callback::responseHeaderReceived ( const QHttpResponseHeader & resp )  {
  qDebug() << "Headers: " << resp.toString();

}

